<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Exception\Handler;

use GuzzleHttp\Client;
use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\ExceptionHandler\ExceptionHandler;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Psr\Http\Message\ResponseInterface;
use Throwable;

class AppExceptionHandler extends ExceptionHandler
{
    /**
     * @var StdoutLoggerInterface
     */
    protected $logger;

    public function __construct(StdoutLoggerInterface $logger)
    {
        $this->logger = $logger;
    }

    public function handle(Throwable $throwable, ResponseInterface $response)
    {
//        ddTitle('errStr');
//        $msg = 'aaa';
//        $this->push_by_error([], $msg);
        $this->logger->error(sprintf('%s[%s] in %s', $throwable->getMessage(), $throwable->getLine(), $throwable->getFile()));
        $this->logger->error($throwable->getTraceAsString());
        return $response->withHeader('Server', 'Hyperf')->withStatus(500)->withBody(new SwooleStream('Internal Server Error.'));
    }

    public function isValid(Throwable $throwable): bool
    {
        return true;
    }

    public function push_by_error($data, &$msg = '')
    {
        $timestamp = time() * 1000;

        $secret = 'SECe2075482f460a34b92560dd3c383f08a8e18fb5e3bef9363833098eb0ad74f50';

        $sign_msg = $timestamp . "\n" . $secret;

        $final_sign = urlencode(base64_encode(hash_hmac('sha256', $sign_msg, $secret, true)));

        $access_token = '3331eb402ed245cb4180548f53a042724a6c7231bba4fdca3eb8e22a9bf2f816';

        $uri = "https://oapi.dingtalk.com/robot/send?access_token=$access_token&timestamp=$timestamp&sign=$final_sign";

        $header = [

            'Accept' => ' application/json',
        ];

        $client = new Client(['timeout' => 5]);

        $res = $client->post($uri, $uri, [
            'json' => $data,
            'headers' => $header,
        ]);
        dd('res', $res);
        $body = $res->getBody();
        $json = $body->getContents();
        $_arr = json_decode($json, true);
        dd('arr', $_arr);
        if (isset($_arr['errcode']) && $_arr['errcode'] == 0) {
            return true;
        } else {
            return false;
        }

    }
}
